package at.codebase.web.servlets.user;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EImageDao;
import at.codebase.db.dao.EUserDao;
import at.codebase.db.entities.EImage;
import at.codebase.db.entities.EUser;
import at.codebase.web.util.LocalRequest;
import at.codebase.web.util.LocalRequest.RequestInformation;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 *
 */
public class UserUploadHandler extends HttpServlet {
	
	private static BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	private static ImagesService imagesService = ImagesServiceFactory.getImagesService();
	
	private static int MAX_IMAGE_HEIGHT = 800;
	private static int MAX_IMAGE_WIDTH = 800;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		RequestInformation requestInformation = LocalRequest.create(req);
		if(requestInformation.isUserLoggedIn()){
			
			EUser user = requestInformation.getUser();
			
			if(user != null){

				Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
				List<BlobKey> blobKeys = blobs.get("uploadFile");
				if(blobKeys.size() == 1){
					BlobKey orgBlobKey = blobKeys.get(0);
					Image orgImage = ImagesServiceFactory.makeImageFromBlob(orgBlobKey);
					
					Transform resizeTransform = ImagesServiceFactory.makeResize(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
					
					try {
						Image image = imagesService.applyTransform(resizeTransform, orgImage);
						
						/**
						 * 
						 */
						FileService fileService = FileServiceFactory.getFileService();
						AppEngineFile file = fileService.createNewBlobFile("image/png");
						
						boolean lock = true;
						@SuppressWarnings("resource")
						FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
						
						ByteBuffer buffer = ByteBuffer.wrap(image.getImageData());
						writeChannel.write(buffer);
						
						writeChannel.closeFinally();
						
						// Now read from the file using the Blobstore API
						BlobKey blobKey = fileService.getBlobKey(file);
						/**
						 * 
						 */
						
						EImage imageEntity = EImage.createUserImage(EUser.key(requestInformation.getUser().getId()),
								blobKey, image.getWidth(), image.getHeight());
						EImageDao.addImage(imageEntity);
						
						user.setImage(EImage.key(imageEntity.getId()));
						EUserDao.saveUser(user);
						
						Log.logUser(
								requestInformation.getUser().getId(),
								"User (userid="
										+ requestInformation.getUser().getId()
										+ ") updated his profile image (imageid="
										+ imageEntity.getId() + ")");
						
						blobstoreService.delete(orgBlobKey);
						
					}catch (IllegalArgumentException e){
						//Invalid Image...
					}
						
				}

			}
			
			res.sendRedirect("/user/profile");
			
		}
			
	}
	
}
